﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;

namespace Gronia.WPF.Classes
{
    public static class ColorUtilities
    {
        public static Color HsvToRgb(double h, double s, double v)
        {
            byte r, g, b;
            HsvToRgb(h, s, v, out r, out g, out b);
            return Color.FromRgb(r, g, b);
        }

        public static void HsvToRgb(double h, double s, double v, out byte r, out byte g, out byte b)
        {
            h = MathUtilities.Clamp(h, 360);
            double R, G, B;
            if (v <= 0)
            {
                R = G = B = 0;
            }
            else if (s <= 0)
            {
                R = G = B = v;
            }
            else
            {
                double hf = h / 60;
                int i = (int)Math.Floor(hf);
                double f = hf - i;
                double pv = v * (1 - s);
                double qv = v * (1 - s * f);
                double tv = v * (1 - s * (1 - f));
                switch (i)
                {
                    case 0: { R = v; G = tv; B = pv; } break;
                    case 1: { R = qv; G = v; B = pv; } break;
                    case 2: { R = pv; G = v; B = tv; } break;
                    case 3: { R = pv; G = qv; B = v; } break;
                    case 4: { R = tv; G = pv; B = v; } break;
                    case 5: { R = v; G = pv; B = qv; } break;
                    case 6: { R = v; G = tv; B = pv; } break;
                    case -1: { R = v; G = pv; B = qv; } break;
                    default: { R = G = B = v; } break;
                }
            }
            r = (byte)MathUtilities.Clamp((int)(R * 255), 0, 255);
            g = (byte)MathUtilities.Clamp((int)(G * 255), 0, 255);
            b = (byte)MathUtilities.Clamp((int)(B * 255), 0, 255);
        }
    }
}